package Control;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import Entity.MsgPackage;

import GUI.Login;
import GUI.ScreenManager;
import Entity.User;

/**
 * Controls the instance of LoginControl
 * This class sends and gets data from the server 
 * and display it on the panel.
 * @author Aviat
 *
 */ 
public class LoginControl {
	private Login logInPanel;
	private MsgPackage LonInMsg;
	private User user;
	private Object result;
	
	/**
	 * the constructor
	 */
	public LoginControl(){
		logInPanel = new Login();
		LonInMsg= new MsgPackage();
		user= new User();
		result=null;
	}
	
	public User getUser() {
		return user;
	}
	/**
	 * 
	 * @return logInPanel
	 */
	public Login getlogInPanel(){
		return logInPanel;
	}
	
	/**
	 * This method sends user name and password to the server
	 *  The server sends an answer (received from query from database) 
	 *  if the user name and password match return true
	 *  else an error display.
	 * @return boolean
	 */
	public boolean loginReq_pressed(){
		String x = logInPanel.getTextArea_userName().getText();
		String y = logInPanel.getTextArea_password().getText();
		if(x==null||y==null){
			JOptionPane.showMessageDialog(null, "Not all the fileds all the fill", "ERROR", JOptionPane.ERROR_MESSAGE);

		return false;	
		}
		
		else{
		user.setUserName(Integer.parseInt(logInPanel.getTextArea_userName().getText()));
		user.setPassword(logInPanel.getTextArea_password().getText());
		LonInMsg.setObject(user);
		LonInMsg.setOp_code(OP_CODE.LOGIN);
		ScreenManager.getConnection().accept(LonInMsg);
		
		while(ScreenManager.getConnection().getAnswerReceivedFlag() == false);	//wait until flag is changed and shows that result was received from server
    	
    	Object o = ScreenManager.getConnection().getResultobject();
    	result = (Boolean)o;
		if ((Boolean) result){
			LonInMsg.setOp_code(OP_CODE.GET_PER);
			ScreenManager.getConnection().accept(LonInMsg);
			while(ScreenManager.getConnection().getAnswerReceivedFlag() == false);	//wait until flag is changed and shows that result was received from server
	    	
	    	Object w = ScreenManager.getConnection().getResultobject();
	    	result = (User)w;
	    	user=(User) result;
			
		}
		else{
			JOptionPane.showMessageDialog(null, "User does not exsits!", "ERROR", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		}
		return true;
		}
	
}